<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-row>
                <el-col>
                    <!-- 添加角色按钮 -->
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-row>
                <el-table :data="rolesList" style="width: 100%" border stripe>
                    <!-- 展开列 -->
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            <el-row :class="['bdbottom', 'vcenter', { bdtop: I1 === 0 }]"
                                v-for="(C1, I1) in scope.row.children" :key="C1.id">
                                <!-- 渲染一级权限 -->
                                <el-col :span="5">
                                    <el-tag closable @close="removeRightById(scope.row, C1.id)">{{ C1.authName }}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 渲染二级和三级权限 -->
                                <el-col :span="19">
                                    <!-- 通过 for 循环嵌套渲染二级权限 -->
                                    <el-row :class="['vcenter', { bdtop: I2 !== 0 }]" v-for="(C2, I2) in C1.children"
                                        :key="C2.id">
                                        <!-- 渲染二级权限 -->
                                        <el-col :span="6">
                                            <el-tag type="success" closable @close="removeRightById(scope.row, C2.id)">{{
                                                C2.authName }}</el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                        <!-- 渲染三级权限 -->
                                        <el-col :span="18">
                                            <el-tag type="warning" v-for="(C3) in C2.children" :key="C3.id" closable
                                                @close="removeRightById(scope.row, C3.id)">{{ C3.authName }}</el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>
                    <!-- 索引列 -->
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column prop="roleName" label="角色名称">
                    </el-table-column>
                    <el-table-column prop="roleDesc" label="角色描述">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-row>
                                <el-col>
                                    <!-- 修改按钮 -->
                                    <el-button type="primary" icon="el-icon-edit" size="mini"
                                        @click="showEditForm(scope.row.id)">编辑</el-button>
                                    <!-- 删除按钮 -->
                                    <el-button type="danger" icon="el-icon-delete" size="mini"
                                        @click="removeRoles(scope.row.id)">删除</el-button>
                                    <!-- 分配角色按钮 -->
                                    <el-button type="warning" icon="el-icon-setting" size="mini"
                                        @click="showSetRightDialog(scope.row)">分配权限</el-button>
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
        </el-card>
        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="FormRules" ref="addFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="详细">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="editForm" :rules="FormRules" ref="editFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="详细">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 权限分配对话框 -->
        <el-dialog title="分配权限" :visible.sync="setDialogVisible" width="50%" @close="setDialogClosed">
            <!-- 树形控件 -->
            <el-tree :data="rightslist" :props="treeProps" default-expand-all show-checkbox node-key="id"
                :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'Roles',
    data() {
        return {
            // 角色列表
            rolesList: [],
            // 添加角色
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            // 编辑角色
            editForm: {},
            // 权限数据
            rightslist: [],
            // 控制编辑角色对话框显示与隐藏
            editDialogVisible: false,
            // 控制添加角色对话框显示与隐藏
            addDialogVisible: false,
            // 控制分配权限对话框显示与隐藏
            setDialogVisible: false,
            // 树形控件的属性绑定对象
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            // 默认选中的节点id值数组
            defKeys: [],
            // 当前即将分配权限的角色id
            roleId:'',
            // 表单验证
            FormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
                ]
            }
        }
    },
    mounted() {
        this.getRolesList()
    },
    methods: {
        // 获取所有角色列表
        async getRolesList() {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
            this.rolesList = res.data
        },
        // 监听用户对话框的关闭事件
        addDialogClosed() {
            this.$refs.addFormRef.resetFields()
        },
        // 添加角色
        addRoles() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                //发起表单添加角色请求
                const { data: res } = await this.$http.post('roles', this.addForm)
                // console.log(res);
                if (res.meta.status !== 201) return this.$message.error('添加角色失败！')

                this.$message.success('添加角色成功')
                // 隐藏添加角色的对话框
                this.addDialogVisible = false
                // 重新请求角色列表数据（刷新列表）
                this.getRolesList()
            })
        },
        // 删除角色
        async removeRoles(id) {
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户确认删除，则返回值为字符串 confirm
            // 如果用户取消了删除，则返回值为字符串 cancel
            if (confirmResult === 'confirm') {
                const { data: res } = await this.$http.delete(`roles/${id}`)
                if (res.meta.status !== 200) return this.$message.error('删除角色失败')
                this.$message.success('删除角色成功')
                this.getRolesList()
            } else {
                this.$message.info('已取消删除')
            }
        },
        // 监听用户对话框的关闭事件
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        // 展开角色编辑对话框
        async showEditForm(id) {
            const { data: res } = await this.$http.get(`roles/${id}`)
            if (res.meta.status !== 200) return this.$message.error('角色查询失败！')
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 编辑角色
        editRoles() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                //发起表单添加角色请求
                const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
                console.log(res);
                if (res.meta.status !== 200) return this.$message.error('编辑角色失败！')

                this.$message.success('编辑角色成功')
                // 隐藏添加角色的对话框
                this.editDialogVisible = false
                // 重新请求角色列表数据（刷新列表）
                this.getRolesList()
            })
        },
        // 点击删除三级权限标签
        async removeRightById(role, rightId) {
            // 弹窗用户是否要删除
            const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户确认删除，则返回值为字符串 confirm
            // 如果用户取消了删除，则返回值为字符串 cancel
            if (confirmResult === 'confirm') {
                const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if (res.meta.status !== 200) return this.$message.error('删除权限失败')
                this.$message.success('删除权限成功')
                // this.getRolesList()
                role.children = res.data
            } else {
                this.$message.info('已取消删除')
            }
        },
        // 展示分配权限对话框
        async showSetRightDialog(role) {
            this.roleId = role.id
            // 获取所有权限数据
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) return this.$message.error('获取权限数据失败！')
            // 把获取到的权限数据保存到 data 中
            this.rightslist = res.data
            // 递归获取三级节点数据
            this.getLeafKeys(role, this.defKeys)
            this.setDialogVisible = true
        },
        // 通过递归的形式，获取角色下所有三级权限的 id ，并保存到 defKeys 数组中
        getLeafKeys(node, arr) {
            //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
            //如果当前节点不包含children属性，则表示node为三级权限
            if (!node.children) {
                return arr.push(node.id)
            }
            //递归调用
            node.children.forEach(item => this.getLeafKeys(item, arr))
        },
        // 监听分配权限对话框关闭事件
        setDialogClosed(){
            this.defKeys = []
        },
        // 点击分配权限
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
            if(res.meta.status !== 200) return this.$message.error('分配权限失败！')
            this.$message.success('分配权限成功！')
            this.getRolesList()
            this.setDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.bdbottom {
    border-bottom: 1px solid #eee;
}

.bdtop {
    border-top: 1px solid #eee;
}

.el-tag {
    margin: 7px;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>